package com.wasin.server.handler;

import com.diboot.core.exception.BusinessException;
import com.diboot.core.handler.DefaultExceptionHandler;
import com.diboot.core.vo.Status;
import com.wasin.server.config.TraceIDConfig;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用异常处理类
 *
 * @author wasin
 * @version 1.0.0
 * @date 2021-9-13
 * Copyright © jiqingwuxian
 */
@RestControllerAdvice
@Slf4j
public class GeneralExceptionHandler extends DefaultExceptionHandler {

    /**
     * 业务异常捕获
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public Map<String, Object> handleBusinessException(HttpServletRequest request, BusinessException e) {
        e.printStackTrace();
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", e.getStatus().code());
        map.put("url", request.getRequestURL().toString());
        map.put("msg", e.getMessage());
        map.put("traceId", MDC.get(TraceIDConfig.TRACE_ID_FLAG));
        return map;
    }

    /**
     * 系统异常
     * @param request
     * @param e
     * @return
     */
    @Override
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> handleException(HttpServletRequest request, Exception e) {
        e.printStackTrace();
        Map<String, Object> map = new HashMap<>(4);
        map.put("code", Status.FAIL_EXCEPTION.code());
        map.put("url", request.getRequestURL().toString());
        map.put("msg", e.getMessage());
        map.put("traceId", MDC.get(TraceIDConfig.TRACE_ID_FLAG));
        return map;
    }


}

